package kandl.automation.reporting.testrail;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestTemplate;

import java.util.List;

import kandl.automation.reporting.testrail.model.TestRailPlan;
import kandl.automation.reporting.testrail.model.TestRailTest;
import kandl.automation.reporting.testrail.model.TestRailTestResult;

@Repository
public class TestRailRepository {

    private final RestTemplate restTemplate;

    private final String baseUrl;

    public TestRailRepository(String baseUrl, RestTemplate restTemplate) {
        this.baseUrl = baseUrl;
        this.restTemplate = restTemplate;
    }

    public TestRailTestResult postTestResult(String runId, String caseId, TestRailTestResult testResult) {
        return restTemplate.postForObject(baseUrl + "add_result_for_case/{run_id}/{case_id}", testResult, TestRailTestResult.class, runId, caseId);
    }

    public TestRailPlan getPlan(String planId) {
        return restTemplate.getForObject(baseUrl + "get_plan/{plan_id}", TestRailPlan.class, planId);
    }

    public List<TestRailTest> getTests(String runId) {
        ParameterizedTypeReference<List<TestRailTest>> typeRef = new ParameterizedTypeReference<List<TestRailTest>>() {};
        ResponseEntity<List<TestRailTest>> response = restTemplate.exchange(baseUrl + "get_tests/{run_id}", HttpMethod.GET, null, typeRef, runId);
        return response.getBody();
    }
}
